package com.example.mynewsapp.adapter

import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.bumptech.glide.load.engine.DiskCacheStrategy
import com.example.mynewsapp.R
import com.example.mynewsapp.model.NewsItem
import kotlinx.android.synthetic.main.news_item.view.*

class NewsAdapter (var List: List<NewsItem>, private val context: Context) : RecyclerView.Adapter<NewsAdapter.ViewHolder>() {

    var mOnRecyclerViewItemClick: OnRecyclerViewItemClick? = null

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        val itemView = LayoutInflater.from(parent.context).inflate(R.layout.news_item, parent, false)
        return ViewHolder(itemView)
    }

    override fun getItemCount(): Int {
        return List.size
    }

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        val currentItem = List[position]

        if (currentItem.image == null) {
            holder.imageView.setImageResource(R.drawable.ic_broken_image)
        } else {
            Glide.with(context)
                .load(currentItem.image)
                .diskCacheStrategy(DiskCacheStrategy.ALL)
                .into(holder.imageView)
        }
        holder.textView1.text = currentItem.update // 更新时间
        holder.textView2.text = currentItem.country// 出版国家
        holder.textView3.text = currentItem.title  // 新闻描述
        holder.textView4.text = currentItem.date   // 新闻时间

        // item点击事件的处理
        holder.content.setOnClickListener {
            mOnRecyclerViewItemClick?.OnItemClick(holder.content,currentItem,position)
        }

        holder.content.setOnLongClickListener {
            mOnRecyclerViewItemClick?.OnLongClick(holder.content,currentItem,position)
            false
        }

    }

    class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        val content = itemView.findViewById<View>(R.id.newsItem)
        val imageView: ImageView = itemView.news_image
        val textView1: TextView = itemView.news_item_update
        val textView2: TextView = itemView.news_item_publish
        val textView3: TextView = itemView.news_item_desc
        val textView4: TextView = itemView.news_item_time
    }

    interface OnRecyclerViewItemClick {
        fun OnItemClick(view: View?, t: NewsItem, position: Int)
        fun OnLongClick(view: View?, t: NewsItem, position: Int)
    }

}